#include "face.h"
#include "ui_face.h"

#include <QThread>
#include <QTimer>

face::face(QWidget *parent) :
    QWidget(parent),
    networkManager(new QNetworkAccessManager(this))// 初始化网络管理器
    ,ui(new Ui::face)
{
    ui->setupUi(this);
    udpSocket = new QUdpSocket(this);
    // 绑定端口，监听所有地址上的数据
    if (udpSocket->bind(QHostAddress("192.168.137.1"), 8004)) {
        qDebug() << "UDP端口 8004";
    } else {
        qDebug() << "UDP 绑定失败";
        return;
    }
    connect(udpSocket,&QUdpSocket::readyRead,this,&face::readPendingDatagrams);


}

face::~face()
{
    delete ui;

}

// 将图片转换为 Base64
QString face::pixmapToBase64(const QPixmap &pixmap) {
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    if (!buffer.open(QIODevice::WriteOnly)) {
        qDebug() << "Failed to open buffer for Base64 encoding.";
        return QString();
    }
    pixmap.save(&buffer, "JPEG");
    return QString::fromLatin1(byteArray.toBase64());
}

// 获取 Access Token
void face::requestAccessToken() {
    QUrl tokenUrl("https://aip.baidubce.com/oauth/2.0/token");
    QUrlQuery query;
    query.addQueryItem("grant_type", "client_credentials");
    query.addQueryItem("client_id", "3o6DyvJlPL564p9EX3QT2VVd");
    query.addQueryItem("client_secret", "VV91z1PkI4U7TyVkr8mi7BB2861VzQd7");
    tokenUrl.setQuery(query);

    QNetworkRequest tokenRequest(tokenUrl);
    QNetworkReply *tokenReply = networkManager->get(tokenRequest);
    connect(tokenReply, &QNetworkReply::finished, this, &face::onAccessTokenReceived);

    qDebug() << "Access token request sent.";
}

// Access Token 请求回调
void face::onAccessTokenReceived() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply) return;

    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(response);
        if (doc.isObject() && doc.object().contains("access_token")) {
            accessToken = doc.object().value("access_token").toString();
            qDebug() << "Access token received:" << accessToken;

            // Access Token 获取成功后发送人脸识别请求
            sendFaceRecognitionRequest(lastBase64Image);
        } else {
            qDebug() << "Failed to parse access token response.";
        }
    } else {
        qDebug() << "Network error while fetching access token:" << reply->errorString();
    }

    reply->deleteLater();
}

// 发送人脸识别请求
void face::sendFaceRecognitionRequest(const QString &base64Image) {
    if (accessToken.isEmpty()) {
        // 如果没有 Access Token，先获取
        qDebug() << "Access token is empty. Requesting a new one.";
        lastBase64Image = base64Image; // 保存 Base64 图片
        requestAccessToken();
        return;
    }

    QUrl url("https://aip.baidubce.com/rest/2.0/face/v3/search");
    QUrlQuery query;
    query.addQueryItem("access_token", accessToken);
    url.setQuery(query);

    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    // 构造 JSON 数据
    QJsonObject json;
    json["group_id_list"] = "12";
    json["image"] = base64Image;
    json["image_type"] = "BASE64";
    QJsonDocument doc(json);
    QByteArray jsonBody = doc.toJson(QJsonDocument::Compact);

    QNetworkReply *reply = networkManager->post(request, jsonBody);
    connect(reply, &QNetworkReply::finished, this, &face::onFaceRecognitionFinished);

    // qDebug() << "Face recognition request sent with JSON body:" << jsonBody;
}

bool face::getuser()
{
   if(userInfoData.score >90)
   {
        emit log_in_yes(userInfoData.userId);
         return  true;
   }
   return  false;
}

// 人脸识别请求回调
void face::onFaceRecognitionFinished() {
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply) return;

    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(response);
        if (doc.isObject()) {
            QJsonObject root = doc.object();
            if (root.contains("result") && root["result"].isObject()) {
                QJsonObject resultObj = root["result"].toObject();
                if (resultObj.contains("user_list") && resultObj["user_list"].isArray()) {
                    QJsonArray userArray = resultObj["user_list"].toArray();
                    if (!userArray.isEmpty() && userArray.first().isObject()) {
                        QJsonObject userObj = userArray.first().toObject();

                        // 设置 userInfoData 的值
                        userInfoData.groupId = userObj.value("group_id").toString();
                        userInfoData.userId = userObj.value("user_id").toString();
                        userInfoData.userInfo = userObj.value("user_info").toString();
                        userInfoData.score = userObj.value("score").toDouble();


                        QString temp_str;
                        temp_str =  "User ID:" + userInfoData.userId
                                   + "\nGroup ID:" + userInfoData.groupId
                                   + "\nUser Info:" + userInfoData.userInfo
                                   + "\nScore:" +QString("%1").arg(userInfoData.score)
                                   + "\nmaxScore:" +QString("%1").arg (maxscore);
                        ui->label_show->setText(temp_str);
                        if(userInfoData.score >  maxscore)
                        {
                            maxscore=userInfoData.score;
                            qDebug() << "maxScore:" << maxscore;
                        }
                        // 打印数据
                    /*    qDebug() << "User ID:" << userInfoData.userId
                                 << "Group ID:" << userInfoData.groupId
                                 << "User Info:" << userInfoData.userInfo
                                 << "Score:" << userInfoData.score
                                  <<"maxScore:" << maxscore;
                   */ }
                }
            }
        }
    } else {
        qDebug() << "Network error during face recognition:" << reply->errorString();
    }

    reply->deleteLater();
}

void face::readPendingDatagrams()
{
    // 循环读取所有可用数据包
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());

        QHostAddress sender;
        quint16 senderPort;

        // 接收数据包
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        ui->label_video->setAlignment(Qt::AlignCenter);

        // 将QByteArray转换为QImage
     //  QImage image;
        if (image.loadFromData(datagram)) {
            // 将QImage转换为QPixmap并设置到QLabel上
            QLabel label;
            QPixmap pixmap = QPixmap::fromImage(image);
            ui->label_video->setPixmap(pixmap);
            ui->label_video->show();

            connect(this->ui->pushButton, &QPushButton::pressed,this,[=]()
            {
                if (isRequestInProgress) {
                      return; // 如果请求正在进行，直接返回
                  }
                 qDebug() << "俺来了.=======================================================================";
                 QString Base64_img = pixmapToBase64(pixmap);
                 sendFaceRecognitionRequest(Base64_img);


                 connect(this, &face::onFaceRecognitionFinished, this, [=]() {
                      isRequestInProgress = false; // 请求完成后可以再次触发
                  });
            });
         //  qDebug() << "load image from data.";

        } else {
            // 如果图片加载失败，输出错误信息
            qDebug() << "Failed to load image from data.";
        }

      //  qDebug() << "Home Received data:" << datagram;
    //   qDebug() << "From:" << sender.toString() << ":" << senderPort;
    }
}

void face::on_pushButton_2_clicked()
{
    if(maxscore >90)
    {
        emit log_in_yes(userInfoData.userId);
        QMessageBox::question(this ,"用户登录成功" , "欢迎回家"+userInfoData.userId, QMessageBox::Ok);
        maxscore=0;
        close();
    }else
    {
        QMessageBox::question(this ,"用户登录失败" , "人脸不匹配", QMessageBox::Ok);
    }

}
